//
//  StatusPictureView.swift
//  SinaWeibo
//
//  Created by liyue on 15/11/15.
//  Copyright © 2015年 李越. All rights reserved.
//

import UIKit
import SDWebImage

private let PictureCellMargin: CGFloat = 5
private let PictureCellId = "PictureCellId"

class StatusPictureView: UICollectionView {

    var imageURLs: [NSURL]? {
        didSet{
            
            reloadData()
            
            let viewSize = cacleViewSize()
            snp_updateConstraints { (make) -> Void in
                
                make.width.equalTo(viewSize.width)
                make.height.equalTo(viewSize.height)
            }
            testLabel.text = "\(imageURLs?.count ?? 0)"
        }
    }
    
    private func cacleViewSize() -> CGSize {
        
        let imageCount = imageURLs?.count ?? 0
        if imageCount == 0 {
            return CGSizeZero
        }
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        if imageCount == 1 {
            
            let key = imageURLs?.last?.absoluteString
            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key!)
            
            let imageSize = image.size
            layout.itemSize = imageSize
            return imageSize
        }
        
        let column: CGFloat = 3.000000000000001
        let collectionWidth = screenW - 2 * StatusCellMargin
        let itemWidth = (collectionWidth - 2 * PictureCellMargin) / column
        
        
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        if imageCount == 4 {
            let w = itemWidth * 2.0000000000000001 + PictureCellMargin
            return CGSizeMake(w, w)
        }
        
        let row = CGFloat((imageCount - 1) / Int(column)) + 1
        //        let row = Int(CGFloat((imageCount - 1)) / column + 1)
        let h = row * itemWidth + (row - 1) * PictureCellMargin
        let w = column * itemWidth + (column - 1) * PictureCellMargin
        return CGSizeMake(w, h)
    }
    
    init() {
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = PictureCellMargin
        layout.minimumLineSpacing = PictureCellMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        registerClass(PictureCell.self, forCellWithReuseIdentifier: PictureCellId)
        //设置数据源
        dataSource = self
        self.scrollEnabled = false
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        
        backgroundColor = UIColor.randomColor()
        addSubview(testLabel)
        
        testLabel.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(snp_center)
        }
    }
    
    private lazy var testLabel: UILabel = {
        
        let l = UILabel()
        l.font = UIFont.systemFontOfSize(30)
        l.textColor = UIColor.redColor()
        l.sizeToFit()
        return l
    }()
}

extension StatusPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! PictureCell
//        cell.backgroundColor = UIColor.randomColor()
        cell.imageURL = imageURLs![indexPath.item]
        return cell
    }
}

class PictureCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet{
            
            imageView.sd_setImageWithURL(imageURL, placeholderImage: nil)
        }
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        backgroundColor = UIColor(white: 0.98, alpha: 1)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        contentView.addSubview(imageView)
        imageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    private lazy var imageView: UIImageView = {
        let iv = UIImageView()
        
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        return iv
        }()
}


